<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item>考生列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="examinee_list_content">
        <!-- 按钮栏 -->
        <el-row type="flex" justify="space-between">
          <el-col :span="18">
            <div class="examinee_list_top">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                @click="examineeAdd()"
                >添加考生</el-button
              >
              <el-upload
                class="upload-demo"
                :action="actionUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :name="uploadName"
                style="margin-left: 10px"
              >
                <el-button size="mini" type="primary" icon="el-icon-upload2"
                  >导入考生</el-button
                >
              </el-upload>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-download"
                style="margin-left: 10px"
                @click="downloadTemplateFn()"
              >
                下载模板
              </el-button>
              <el-button size="mini" type="primary" @click="batchUpload()"
                >批量上传照片</el-button
              >

              <div class="examinee_list_top_tips">( 报名前请先添加考生 )</div>
            </div>
          </el-col>
          <el-col :span="4" style="display: flex; justify-content: flex-end">
            <el-popover
              placement="left-end"
              width="800"
              trigger="click"
              @show="popoverShow()"
            >
              <div
                v-if="errorListData != undefined && errorListData.length > 0"
              >
                <el-row>
                  <el-col :span="24">
                    <el-table
                      :data="errorListData"
                      border
                      size="mini"
                      style="width: 100%"
                    >
                      <el-table-column
                        type="index"
                        label="序号"
                        width="50"
                        align="center"
                      >
                      </el-table-column>

                      <el-table-column
                        prop="content"
                        label="错误内容"
                        align="center"
                      >
                      </el-table-column>

                      <el-table-column
                        prop="level"
                        label="错误等级"
                        align="center"
                        width="100"
                      ></el-table-column>

                      <el-table-column
                        prop="created_at"
                        label="错误时间"
                        align="center"
                      ></el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <div class="examinee_list_pagination">
                      <el-pagination
                        @size-change="errorListSizeChange"
                        @current-change="errorListCurrentChange"
                        :current-page="errorListCurrentPage"
                        :page-sizes="errorListPageSizes"
                        :page-size="errorListPageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="errorListTotal"
                      >
                      </el-pagination>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <el-row v-else>
                <el-empty description="暂无错误日志"></el-empty>
              </el-row>
              <el-button size="mini" type="primary" slot="reference"
                >错误日志</el-button
              >
            </el-popover>
          </el-col>
        </el-row>
        <!-- 搜索栏 -->
        <el-row>
          <el-col :span="24">
            <div class="examinee_list_search">
              <div>筛选：</div>
              <el-select
                v-model="levelSearch"
                placeholder="请选择篮球等级"
                size="mini"
                style="width: 150px; margin-left: 5px"
                clearable
                @change="levelSearchFn"
              >
                <el-option label="无" :value="0"></el-option>
                <el-option
                  v-for="item in levelList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                >
                </el-option>
              </el-select>
              <el-select
                v-model="imgHasSearch"
                placeholder="是否上传证件照"
                size="mini"
                style="width: 150px; margin-left: 5px"
                clearable
                @change="imgHasSearchFn"
              >
                <el-option
                  v-for="item in imgHasSearchOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-input
                v-model="searchKey"
                placeholder="请输入考生姓名"
                size="mini"
                style="width: 150px; margin-left: 5px"
              ></el-input>
              <el-button
                type="primary"
                size="mini"
                style="margin-left: 5px"
                @click="searchFn()"
                >搜索</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 数据列表 -->
        <div
          v-if="examineeListData != undefined && examineeListData.length > 0"
        >
          <el-row>
            <el-col :span="24">
              <el-table
                :data="examineeListData"
                border
                size="mini"
                style="width: 100%"
                :cell-style="cellStyleFn"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                >
                </el-table-column>

                <el-table-column
                  prop="name"
                  label="考生姓名"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="height"
                  label="身高"
                  width="80"
                  align="center"
                >
                </el-table-column>

                <el-table-column
                  prop="identity_number"
                  label="证件号"
                  align="center"
                ></el-table-column>

                <!-- <el-table-column
                  prop="ogname"
                  label="所属机构"
                  align="center"
                ></el-table-column> -->

                <el-table-column
                  prop="real_level"
                  label="篮球等级"
                  align="center"
                  :formatter="formatterLevelFn"
                ></el-table-column>

                <el-table-column
                  label="证件照"
                  align="center"
                  :formatter="formatterHasImgFn"
                ></el-table-column>

                <el-table-column
                  label="操作"
                  width="300"
                  itemprop=""
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-document"
                      class="examinee_detail_btn"
                      @click="examineeDetail(scope.$index, scope.row)"
                      >查看</el-button
                    >
                    <el-button
                      size="mini"
                      type="primary"
                      icon="iconfont icon-bianji"
                      class="examinee_edit_btn"
                      @click="examineeEdit(scope.$index, scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete-solid"
                      class="examinee_delete_btn"
                      @click="examineeDelete(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="examinee_list_pagination">
                <el-pagination
                  @size-change="listSizeChange"
                  @current-change="listCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row v-else>
          <el-empty description="暂无考生"></el-empty>
        </el-row>
      </div>
    </el-row>

    <!-- 弹框 -->
    <el-dialog
      title="批量上传照片"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="dialogClose"
    >
      <el-row type="flex" justify="center">
        <el-col :span="24">
          <el-upload
            class="upload-demo"
            :action="batchUploadActionUrl"
            :show-file-list="true"
            :on-success="batchUploadHandleAvatarSuccess"
            :before-upload="batchUploadBeforeAvatarUpload"
            :headers="headers"
            :name="batchUploadName"
            :on-remove="batchUploadHandleAvatarRemove"
            multiple
            :limit="20"
            :on-exceed="batchUploadHandleExceed"
            :file-list="batchUploadFileList"
          >
            <el-button type="primary">选择照片</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogClose()">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveBatchFn()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<style src="../../assets/css/examinee/examineeList.css" scoped></style>

<script>
export default {
  name: "ExamineeList",
  components: {},
  data() {
    return {
      baseAPIUrl: this.$store.state.baseAPIUrl,
      actionUrl: this.$store.state.baseAPIUrl + "/excel/importStu", // 上传路径
      uploadName: "excelfile",
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 上传用token
      levelSearch: "", // 等级筛选
      imgHasSearch: "", // 证件照筛选
      imgHasSearchOptions: [
        {
          value: 1,
          label: "有",
        },
        {
          value: 2,
          label: "无",
        },
      ],
      searchKey: "", // 搜索关键词
      examineeListData: [], // 考生列表
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      levelList: [], // 等级列表
      dialogVisible: false, // 弹窗显示
      batchUploadActionUrl:
        this.$store.state.baseAPIUrl + "/upload/uploadStuPhoto", // 批量上传路径
      batchUploadName: "file",
      fileList: [],
      batchUploadFileList: [],
      loadingKey: false,
      loadingText: "",
      errorListData: [], // 错误日志
      errorListCurrentPage: 1, // 错误日志当前页
      errorListPageSizes: [10, 20, 50, 100], // 错误日志可选页容量
      errorListPageSize: 10, // 错误日志当前页容量
      errorListTotal: 0, // 错误日志总条数
    };
  },
  created: function () {
    this.getListDataFn();
    this.levelList = JSON.parse(JSON.stringify(this.$store.state.levelList));
  },
  methods: {
    // 等级筛选
    levelSearchFn: function (val) {
      this.levelSearch = val;
      this.searchFn();
    },
    // 证件照筛选
    imgHasSearchFn: function (val) {
      this.imgHasSearch = val;
      this.searchFn();
    },
    // 搜索按钮
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 获取列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/mobile/studentList";
      let data = {
        page: this.currentPage,
        perPage: this.pageSize,
        keywords: this.searchKey,
        level: this.levelSearch,
        person_photo_status: this.imgHasSearch,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.examineeListData = response.list;
            that.total = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 获取错误日志列表数据
    geterrorListDataFn: function () {
      let that = this;
      let url = "/mobile/errorIndex";
      let data = {
        page: this.errorListCurrentPage,
        perPage: this.errorListPageSize,
        type: 1,
      };
      this.axios
        .post(url, data)
        .then((response) => {
          if (response.code == 0) {
            that.errorListData = response.errorlog;
            that.errorListTotal = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 日志显示
    popoverShow: function () {
      this.errorListCurrentPage = 1;
      this.geterrorListDataFn();
    },
    // 新增考生
    examineeAdd: function () {
      this.$router.push({
        name: "ExamineeFrom",
        params: {
          key: 1,
        },
      });
    },
    // 修改考生
    examineeEdit: function (index, row) {
      this.$router.push({
        name: "ExamineeFrom",
        params: {
          id: row.id,
          key: 2,
        },
      });
    },
    // 查看考生
    examineeDetail: function (index, row) {
      const routeUrl = this.$router.resolve({
        name: "ExamineeFrom",
      });
      this.$store.commit("set_editExamineeId", row.id);
      this.$store.commit("set_editExamineeKey", 3);
      window.open(routeUrl.href, "_blank");
    },

    // 考试等级格式化
    formatterLevelFn: function (row) {
      let real_level = row.real_level;
      let text = "";
      if (real_level == 0) {
        text = "无";
      } else {
        this.levelList.forEach(function (item) {
          if (item.key == real_level) {
            text = item.value;
          }
        });
      }

      return text;
    },
    // 是否存在证件照格式化
    formatterHasImgFn: function (row) {
      let person_photo = row.person_photo;
      let text = "";
      if (
        person_photo == "" ||
        person_photo == null ||
        person_photo == undefined
      ) {
        text = "无";
      } else {
        text = "有";
      }
      return text;
    },
    // 设置单元格字体颜色
    cellStyleFn: function ({ row, columnIndex }) {
      let style = "";
      if (columnIndex == 5) {
        if (
          row.person_photo == "" ||
          row.person_photo == null ||
          row.person_photo == undefined
        ) {
          style = "color: #F6705E";
        } else {
          style = "color: #8ECF5F";
        }
      }
      return style;
    },
    // 删除考生
    examineeDelete: function (index, row) {
      let that = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        let url = "/mobile/removeStudent";
        let data = {
          stu_id: row.id,
        };
        that.loadingText = "处理中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              that.$message.success("删除成功");
              let next = that.currentPage - 1;
              if (that.examineeListData.length == 1) {
                that.currentPage = next >= 1 ? next : 1;
              }
              that.getListDataFn();
            } else {
              that.$message.error(response.msg);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            console.log(error);
          });
      });
    },
    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 错误日志页容量改变
    errorListSizeChange: function (val) {
      this.errorListCurrentPage = 1;
      this.errorListPageSize = val;
      this.geterrorListDataFn();
    },
    // 错误日志当前页改变
    errorListCurrentChange: function (val) {
      this.errorListCurrentPage = val;
      this.geterrorListDataFn();
    },
    // 上传成功钩子
    handleAvatarSuccess: function (res) {
      if (res.code == 1) {
        this.$message.error(res.msg);
      } else {
        this.$message.success("导入成功");
      }
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      let type = file.name.indexOf(".xlsx");
      if (type == -1) {
        this.$message.error("上传xlsx文件");
        return false;
      }
      return true;
    },
    // 下载模板
    downloadTemplateFn: function () {
      const link = document.createElement("a");
      // 这里是将链接地址url转成blob地址，
      fetch(this.baseAPIUrl + "/download/stu_import_demo1.xlsx")
        .then((res) => res.blob())
        .then((blob) => {
          link.href = URL.createObjectURL(blob);
          // 下载文件的名称及文件类型后缀
          link.download = "stu_import_demo1.xlsx";
          document.body.appendChild(link);
          link.click();
          // 在资源下载完成后 清除 占用的缓存资源
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        });
    },
    // 关闭弹窗
    dialogClose: function () {
      this.dialogVisible = false;
    },
    // 批量上传按钮
    batchUpload: function () {
      this.fileList = [];
      this.batchUploadFileList = [];
      this.$nextTick(function () {
        this.dialogVisible = true;
      });
    },
    // 批量上传成功钩子
    batchUploadHandleAvatarSuccess: function (res) {
      if (res.code == 1) {
        this.$message.error(res.msg);
      } else {
        let obj = {
          image_name: res.file_name,
          image_path: res.file_path,
        };
        this.fileList.push(obj);
      }
    },
    // 批量上传列表移除钩子
    batchUploadHandleAvatarRemove: function (file) {
      let that = this;
      if (file.status == "success") {
        let name = file.response.file_name;
        let index = that.fileList.findIndex((item) => item.image_name === name);
        if (index > -1) {
          that.fileList = that.fileList.splice(index, 1);
        }
      }
    },
    // 批量上传前钩子
    batchUploadBeforeAvatarUpload: function (file) {
      let that = this;
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt3M = file.size / 1024 / 1024 < 3;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
        return false;
      }
      return (
        (isJPG || isPNG) &&
        isLt3M &&
        new Promise(function (resolve, reject) {
          let img = new Image();
          let fileBlobName = null;
          if (window.createObjectURL !== undefined) {
            fileBlobName = window.createObjectURL(file);
          } else if (window.URL !== undefined) {
            fileBlobName = window.URL.createObjectURL(file);
          } else if (window.webkitURL !== undefined) {
            fileBlobName = window.webkitURL.createObjectURL(file);
          }
          img.src = fileBlobName;
          img.onload = () => {
            const cl = img.height / img.width;
            if (cl >= 1.28 && cl <= 1.52) {
              resolve();
            } else {
              that.$message.error("照片尺寸不合规");
              reject();
            }
          };
        })
      );
    },
    batchUploadHandleExceed: function (files) {
      let that = this;
      this.$message.warning(
        `最多可一次性上传20个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + that.fileList.length} 个文件`
      );
    },
    // 提交批量上传
    saveBatchFn: function () {
      let that = this;
      // 校验上传文件是否存在重名
      let setKey = true;
      for (let i = 0; i < this.fileList.length; i++) {
        for (let j = i; j < that.fileList.length; j++) {
          if (
            that.fileList[j].image_name === that.fileList[i].image_name &&
            j != i
          ) {
            setKey = false;
          }
        }
      }
      if (!setKey) {
        that.$message.error("存在重名文件，无法上传！");
      } else {
        this.$confirm("确认上传?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          let url = "/mobile/saveBatchStuPhoto";
          let data = {
            stu_photos: that.fileList,
          };
          that.loadingText = "处理中...";
          that.loadingKey = true;
          that.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("上传成功");
                that.dialogClose();
                let next = that.currentPage - 1;
                if (that.examineeListData.length == 1) {
                  that.currentPage = next >= 1 ? next : 1;
                }
                that.getListDataFn();
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        });
      }
    },
  },
};
</script>
